from django.shortcuts import render,redirect,get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import Image
from .forms import ImageCreateForm
from django.conf import settings
import redis

r = redis.StrictRedis(host=settings.REDIS_HOST,port=settings.REDIS_PORT,db=settings.REDIS_DB)
# Create your views here.

@login_required
def image_create(request):
    """

    :param request:
    :return:
    """
    if request.method == "POST":
        form = ImageCreateForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            new_item = form.save(commit=False)
            new_item.user = request.user
            new_item.save()
            messages.success(request,'Image added successfully')
            return redirect(new_item.get_absolute_url())
    else:
        form = ImageCreateForm()
    return render(request,'images/image/create.html',{'section':'images','form':'form'})

def image_detail(request):
    #image = get_object_or_404(Image,id=id,slug=slug)
    image = Image.objects.all()[0]
    total_views = r.incr('image:{}:views'.format(image.id))
    return render(request,'images/image/detail.html',{
        'section':'images',
        'image':image,
        'total_views':total_views
        })

